<template>
  <div @click="onUpload" class="ok-upload">
    <slot></slot>
    <input ref="ok-file"
           @change="onChange"
           :multiple="multiple"
           :accept="accept"
           class="ok-file"
           type="file"/>
  </div>
</template>

<script type="es6">
export default {
  name: "upload",
  props: {
    multiple: "",
    accept: "",
    isBase64: "",
  },
  data() {
    return {};
  },
  mounted() {
  },
  methods: {
    onUpload() {
      let el = this.$refs['ok-file'];
      el.click();
    },
    base64Url(files) {
      let base64 = [];
      return new Promise(resolve => {
        files.forEach(item => {
          let reader = new FileReader();
          reader.readAsDataURL(item);
          reader.onload = function () {
            base64.push(reader.result);//获取到base64格式图片
            if (base64.length == files.length) {
              resolve(base64);
            }
          };
        });
      });
    },
    async onChange(e) {
      let base64 = [];
      // debugger
      if (this.isBase64) {
        base64 = await this.base64Url(e.target.files)
      }
      // console.log(base64);
      this.$emit("change", {
        "element": e.target,
        "files": e.target.files,
        "base64": base64
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.ok-upload {
  position: relative;
  overflow: hidden;

  .ok-file {
    display: none;
    opacity: 0;
    width: 0;
    height: 0;
    font-size: 0;
  }
}
</style>